package com.ipan.poi.excel.util;

import java.lang.reflect.Field;

import javax.persistence.Entity;
import javax.persistence.Transient;

import com.ipan.poi.excel.config.XlsEntity;
import com.ipan.poi.excel.config.XlsExports;
import com.ipan.poi.excel.config.XlsImports;
import com.ipan.poi.excel.config.XlsRoot;

/**
 * 从实体类生成XML配置文件工具类
 * 生成后，自行做简单修改即可；
 * 
 * @author iPan
 * @version 2013-9-15
 */
public class XlsGenerateCfgUtils {

	public static String pojoToImportXml(Class<?> entity) {
		return pojoToXml(entity, true);
	}
	
	public static String pojoToExportXml(Class<?> entity) {
		return pojoToXml(entity, false);
	}
	
	private static String pojoToXml(Class<?> entity, boolean isImport) {
		Field[] fields = entity.getDeclaredFields();
		if (fields == null || fields.length < 1) {
			return null;
		}
		String result = null;
		XlsRoot root = (isImport) ? new XlsImports() : new XlsExports();
		XlsEntity defEntity = new XlsEntity(root, entity.getName(), entity.getSimpleName());
		for (Field f : fields) {
			defEntity.addProperty(f.getName(), f.getName());
		}
		result = root.addEntity(defEntity).toString();
		return result;
	}
	
	public static String jpaToImportXml(Class<?> entity) {
		return jpaToXml(entity, true);
	}
	
	public static String jpaToExportXml(Class<?> entity) {
		return jpaToXml(entity, false);
	}
	
	private static String jpaToXml(Class<?> entity, boolean isImport) {
		Field[] fields = entity.getDeclaredFields();
		if (fields == null || fields.length < 1) {
			return null;
		}
		if (entity.getAnnotation(Entity.class) == null) {
			throw new RuntimeException("找不到实体类注释！");
		}
		String result = null;
		XlsRoot root = (isImport) ? new XlsImports() : new XlsExports();
		XlsEntity defEntity = new XlsEntity(root, entity.getName(), entity.getSimpleName());
		for (Field f : fields) {
			if (f.getAnnotation(Transient.class) != null) {
				continue ;
			}
			defEntity.addProperty(f.getName(), f.getName());
		}
		result = root.addEntity(defEntity).toString();
		return result;
	}
}
